﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SMS.Domain;
using SMS.Domain.Model;
using System.Collections.ObjectModel;

namespace SMS.Shell.Views
{
    /// <summary>
    /// Interaction logic for InvoiceView.xaml
    /// </summary>
    public partial class InvoiceView : Page
    {
        private Customer _customer;

        private Invoice _invoice;

        public InvoiceView(Customer customer)
        {
            InitializeComponent();

            _customer = customer;
            _panelCustomer.DataContext = _customer;

            _invoice = new Invoice();
            _invoice.Id = Guid.NewGuid();
            _invoice.Customer = _customer;
            _invoice.CustomerId = _customer.Id;
            _invoice.Cargos = new ObservableCollection<SaleCargo>();
            this.DataContext = _invoice;

            this.Loaded += new RoutedEventHandler(InvoiceView_Loaded);
        }

        void InvoiceView_Loaded(object sender, RoutedEventArgs e)
        {
            _listKeywords.ItemsSource = new SmsService().FindKeywords();
        }

        private void _listKeywords_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Keywords keyword = _listKeywords.SelectedItem as Keywords;
            if (keyword != null)
            {
                _gridCargoSource.ItemsSource = new SmsService().FindCargos(keyword);
            }
        }

        private void _btnSelect_Click(object sender, RoutedEventArgs e)
        {
            Cargo cargo = (sender as Button).DataContext as Cargo;
            if (cargo != null)
            {
                bool isExist = false;
                foreach (SaleCargo item in _invoice.Cargos)
                {
                    if (item.CargoId == cargo.Id)
                    {
                        isExist = true;
                        break;
                    }
                }

                if (!isExist)
                {
                    SaleCargo item = new SaleCargo();
                    item.Id = Guid.NewGuid();
                    item.Cargo = cargo;
                    item.CargoId = cargo.Id;
                    item.Price = cargo.Price;
                    item.Count = 1;
                    _invoice.Cargos.Add(item);
                }
                else
                {
                    MessageBox.Show("该商品已存在于发货单中!");
                }
            }
        }

        private void _btnAdd_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
